package com.aidong.login.action;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.aidong.jobs.async.SmsTask;
import com.aidong.jobs.constants.JobConst;
import com.aidong.login.biz.MemberLoginBiz;
import com.aidong.login.biz.MemberReigsterBiz;
import com.aidong.login.entity.Member;
import com.aidong.login.entity.MemberBase;
import com.aidong.util.ImageUpload;
import com.aidong.util.RandomUtil;
import com.aidong.util.ReadPropertiesUtil;
import com.aidong.util.bus.SecurityUtils;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 手机号码登录action
 *
 * @author java
 * @version 1.0 2015.07.03
 */
@ParentPackage("json")
@Namespace("/")
public class MemberLoginAction implements ModelDriven<Member> {

    private Member member;

    @Override
    public Member getModel() {
        if (member == null) {
            member = new Member();
        }
        return member;
    }

    @Autowired
    private MemberLoginBiz loginBiz; // 手机号码登录service
    @Autowired
    private MemberReigsterBiz memberBiz; // 登陆注册service
    @Autowired
    private SmsTask smsTask;

    private Map<String, Object> map; // 返回的json数据

    @JSON
    public Map<String, Object> getMap() {
        return map;
    }

    /**
     * 手机号码登录
     *
     * @return
     */
    @Action(value = "getphonetologin", results = {@Result(name = "succ", type = "json", params = {"root", "map"})})
    public String getPhoneToLogin() {
        try {
            member.setMobilePhone(SecurityUtils.decryptPhoneNo(member.getMobilePhoneEncrypt()));
            String phoneNo = member.getMobilePhone(); // 手机号码
            member.setPassword(
                    SecurityUtils.encryptDbMemberPassword(SecurityUtils.decryptPassword(member.getPasswordEncrypt())));
            String password = member.getPassword(); // 密码
            if (Strings.isNotBlank(phoneNo) && Strings.isNotBlank(password)) {
                Map<String, Object> memberMap = loginBiz.getPhoneToLogin(phoneNo);
                if (memberMap != null) {
                    if (password.equals(memberMap.get("password"))) {
                        map.put("code", 1);
                        map.put("idongId", memberMap.get("idongId"));
                        map.put("nickName", memberMap.get("nickName"));
                        String headUrl = String.valueOf(memberMap.get("headUrl"));
                        if (Strings.isBlank(headUrl)) {
                            map.put("headUrl", "");
                        } else {
                            map.put("headUrl", ReadPropertiesUtil.getIMGREAD(headUrl));
                        }
                        map.put("loginType", 1);
                        // 更新登陆信息
                        member.setIdongId(String.valueOf(memberMap.get("idongId")));
                        loginBiz.editMemberLoginMsg(member);
                        // 检查资料是否完善
                        MemberBase memberBase = loginBiz.getCheckMemberData(Integer.valueOf(member.getIdongId()));
                        map.put("createDate", memberBase.getCreateDate());
                        map.put("orderCount", memberBase.getOrderCount());
                        if (memberBase != null && memberBase.isComplete()) {
                            map.put("dataFlag", "N");
                        } else {
                            map.put("dataFlag", "Y");
                        }
                        return "succ";
                    } else {
                        map.put("code", 0);
                        map.put("msg", "密码错误");
                        return "succ";
                    }
                } else {
                    map.put("code", 0);
                    map.put("msg", "没有该用户");
                    return "succ";
                }
            } else {
                map.put("code", 0);
                map.put("msg", "参数缺失");
                return "succ";
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "系统异常");
            return "succ";
        }
    }

    /**
     * 无密码快捷登陆 无密码快捷登陆手机验证码
     *
     * @return
     */
    @Action(value = "getnotpswlogin", results = {@Result(name = "succ", type = "json", params = {"root", "map"})})
    public String getNotPasswordLogin() {
        map = new HashMap<String, Object>();
        try {
            String phoneNo = member.getMobilePhone(); // 手机号码
            String code = member.getCode();//验证码
            if (StringUtils.isBlank(code)) {
                map.put("code", 0);
                map.put("msg", "请下载最新版本");
                return "succ";
            }
            String[] codeMap = JobConst.codeMap.get(phoneNo);
            if (codeMap == null) {
                map.put("code", 0);
                map.put("msg", "验证码已过期");
                return "succ";
            }

            if (!"".equals(phoneNo) && phoneNo != null) {
                if (!code.equalsIgnoreCase(codeMap[0])) {
                    map.put("code", 0);
                    map.put("msg", "验证码输入有误");
                    return "succ";
                }
                JobConst.codeMap.remove(phoneNo);
                // 获得短信验证码
                String captcha = RandomUtil.randomNumber(6);
                int captchaCode = Integer.valueOf(captcha);
                smsTask.captcha(phoneNo, String.valueOf(captchaCode));
                Map<String, Object> loginMap = loginBiz.getNotPasswordLogin(phoneNo);
                Map<String, Object> resultMap = new HashMap<String, Object>();
                int count = Integer.parseInt(loginMap.get("count").toString());
                if (count > 0) {
                    resultMap.put("idongId", loginMap.get("idongId"));
                    resultMap.put("nickName", loginMap.get("nickName"));
                    String headUrl = String.valueOf(loginMap.get("headUrl"));
                    if (Strings.isBlank(headUrl)) {
                        resultMap.put("headUrl", "");
                    } else {
                        resultMap.put("headUrl", ReadPropertiesUtil.getIMGREAD(headUrl));
                    }
                    resultMap.put("autoCode", captchaCode);
                    resultMap.put("loginType", "1");
                    map.put("code", 1);
                    map.put("result", resultMap);
                    // 更新登陆信息
                    member.setIdongId(String.valueOf(resultMap.get("idongId")));
                    loginBiz.editMemberLoginMsg(member);

                    // 检查资料是否完善
                    MemberBase memberBase = loginBiz.getCheckMemberData(Integer.valueOf(member.getIdongId()));
                    map.put("createDate", memberBase.getCreateDate());
                    map.put("orderCount", memberBase.getOrderCount());
                    if (memberBase != null && memberBase.isComplete()) {
                        map.put("dataFlag", "N");
                    } else {
                        map.put("dataFlag", "Y");
                    }
                    return "succ";
                } else {
                    // 添加新用户
                    Map<String, Object> paraMap = new HashMap<String, Object>();
                    paraMap.put("phoneNo", phoneNo);
                    paraMap.put("loginType", 1);
                    loginBiz.addNotPassRegister(paraMap);

                    String idongId = paraMap.get("idongId").toString();
                    resultMap.put("idongId", idongId);
                    resultMap.put("nickName", "");
                    String headUrl = String.valueOf(loginMap.get("headUrl"));
                    if (Strings.isBlank(headUrl)) {
                        resultMap.put("headUrl", "");
                    } else {
                        resultMap.put("headUrl", ReadPropertiesUtil.getIMGREAD(headUrl));
                    }
                    resultMap.put("autoCode", captchaCode);
                    resultMap.put("loginType", "1");
                    map.put("code", 1);
                    map.put("result", resultMap);
                    // 更新登陆信息
                    member.setIdongId(idongId);
                    loginBiz.editMemberLoginMsg(member);
                    Map<String, Object> coupMap = new HashMap<String, Object>();
                    coupMap.put("idongId", idongId);
                    memberBiz.addTicketsByNewbie(coupMap);
                    // 检查资料是否完善
                    MemberBase memberBase = loginBiz.getCheckMemberData(Integer.valueOf(member.getIdongId()));
                    map.put("createDate", memberBase.getCreateDate());
                    map.put("orderCount", memberBase.getOrderCount());
                    if (memberBase != null && memberBase.isComplete()) {
                        map.put("dataFlag", "N");
                    } else {
                        map.put("dataFlag", "Y");
                    }
                    return "succ";
                }
            } else {
                map.put("code", 0);
                map.put("msg", "参数缺失");
                return "succ";
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "系统异常");
            return "succ";
        }
    }

    /**
     * 第三方登陆
     *
     * @return
     */
    @Action(value = "addthirdlogin", results = {@Result(name = "succ", type = "json", params = {"root", "map"})})
    public String addThirdPartyLogin() {
        map = new HashMap<String, Object>();
        try {
            String usid = member.getUsid(); // 第三方ID号
            String loginType = member.getLoginType(); // 登陆类型

            Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher emojiMatcher = emoji.matcher(member.getScreen_name());
            if (emojiMatcher.find()) {
                member.setScreen_name(emojiMatcher.replaceAll("*"));
            }
            String screen_name = member.getScreen_name(); // 昵称
            String gender = member.getGender(); // 性别
            if (!"".equals(gender) && gender != null) {
                if ("男".equals(gender) || "1".equals(gender)) {
                    gender = "M";
                } else if ("女".equals(gender) || "2".equals(gender)) {
                    gender = "F";
                }
            }
            member.setGender(gender);
            // 是否已经注册为爱动会员
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("loginType", loginType);
            paraMap.put("usid", usid);
            int count = loginBiz.getIfThirdRegisterd(paraMap);
            if (count > 0) {
                // 根据第三方账号查找爱动号
                Map<String, Object> reqMap = new HashMap<String, Object>();
                reqMap.put("loginType", loginType);
                reqMap.put("usid", usid);
                String idongId = loginBiz.getThirdByIdongId(reqMap);
                // 获得第三方账号的头像
                String headUrl = loginBiz.getThirdHeadUrl(idongId);
                // 已经注册，将昵称、登陆类型、idongId返回
                map.put("nickName", screen_name);
                map.put("loginType", loginType);
                map.put("idongId", idongId);
                map.put("headUrl", ReadPropertiesUtil.getIMGREAD(headUrl));
                map.put("code", 1);
                map.put("msg", "登录成功");

                // 更新登陆信息
                member.setIdongId(idongId);
                loginBiz.editMemberLoginMsg(member);

                // 检查资料是否完善
                MemberBase memberBase = loginBiz.getCheckMemberData(Integer.valueOf(member.getIdongId()));
                map.put("createDate", memberBase.getCreateDate());
                map.put("orderCount", memberBase.getOrderCount());
                if (memberBase != null && memberBase.isComplete()) {
                    map.put("dataFlag", "N");
                } else {
                    map.put("dataFlag", "Y");
                }
                return "succ";
            } else {
                // 没有注册、注册之后将昵称、登陆类型、idongId返回
                map.put("orderCount", 0);
                try {
                    member.setProfile_image_url(ImageUpload.outerDownloadOld(member.getProfile_image_url(), "portrait"));
                } catch (Exception e) {

                }
                if (loginType.equals("2")) {// QQ
                    loginBiz.addThirdPartyLoginQqNumber(member);
                } else if (loginType.equals("3")) {// 微信
                    loginBiz.addThirdPartyLoginWeChat(member);
                } else {
                    // 4微博
                    loginBiz.addThirdPartyLoginWeiBo(member);
                }
                // loginBiz.addThirdPartyLogin(member);
                String idongId = member.getIdongId();
                // 获得第三方账号的头像
                String headUrl = loginBiz.getThirdHeadUrl(idongId);
                map.put("nickName", screen_name);
                map.put("loginType", loginType);
                map.put("idongId", idongId);
                map.put("headUrl", ReadPropertiesUtil.getIMGREAD(headUrl));
                map.put("code", 1);
                map.put("msg", "登录成功");
                //member.setProfile_image_url(ImageUpload.outerDownload(ReadPropertiesUtil.getIMGREAD(headUrl), "portrait"));
                // 更新登陆信息
                member.setIdongId(idongId);
                loginBiz.editMemberLoginMsg(member);
                try {
                    /**
                     * 新用户注册发送10元代金券
                     */
                    Map<String, Object> coupMap = new HashMap<String, Object>();
                    coupMap.put("idongId", idongId);
                    memberBiz.addTicketsByNewbie(coupMap);
                } catch (Exception e) {
                }
                // 检查资料是否完善
                MemberBase memberBase = loginBiz.getCheckMemberData(Integer.valueOf(member.getIdongId()));
                map.put("createDate", memberBase.getCreateDate());
                map.put("orderCount", memberBase.getOrderCount());
                if (memberBase != null && memberBase.isComplete()) {
                    map.put("dataFlag", "N");
                } else {
                    map.put("dataFlag", "Y");
                }

                return "succ";
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "系统异常");
            return "succ";
        }
    }

}
